//
//  MemoryCache.swift
//  HinsLive
//
//  Created by haoxian on 2019/5/2.
//  Copyright © 2019 Hins. All rights reserved.
//

import Foundation


struct MemoryCache {
    static var `default` = MemoryCache(name: "global")
    
    let name: String
    
    private var store = [String: Any]()
    
    private let lock = NSRecursiveLock()
    
    init(name: String) {
        self.name = name
    }
    
    mutating func set(value: Any, for key: String) {
        lock.lock(); defer { lock.unlock() }
        store.updateValue(value, forKey: key)
    }
    
    func value(for key: String) -> Any? {
        lock.lock(); defer { lock.unlock() }
        return store[key]
    }
    
    func value<T>(type: T.Type, for key: String) -> T? {
        lock.lock(); defer { lock.unlock() }
        guard let value = store[key] as? T else { return nil }
        return value
    }
    
    @discardableResult
    mutating func removeValue(for key: String) -> Any? {
        lock.lock(); defer { lock.unlock() }
        return store.removeValue(forKey: key)
    }
    
    mutating func removeAll() {
        lock.lock(); defer { lock.unlock() }
        store.removeAll()
    }
}

extension MemoryCache {
    static var feedCategoryKey: String { return "feedCategoryKey" }
}
